// --------------------------------------------------------------------------------------------------------------------
// <copyright file="Vector2.cs" company="Microsoft Corporation">
// The MIT License (MIT)
// 
// Copyright (c) 2014, Microsoft Corporation
// 
// Permission is hereby granted, free of charge, to any person obtaining a copy
//  of this software and associated documentation files (the "Software"), to deal
//  in the Software without restriction, including without limitation the rights
//  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
//  copies of the Software, and to permit persons to whom the Software is
//  furnished to do so, subject to the following conditions:
// 
// The above copyright notice and this permission notice shall be included in
//  all copies or substantial portions of the Software.
// 
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
//  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
//  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
//  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
//  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
//  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
//  THE SOFTWARE.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
namespace Microsoft.Robotics.Numerics
{
    using System;
    using System.ComponentModel;
    using System.Diagnostics;
    using System.Runtime.InteropServices;
    using System.Runtime.Serialization;

    /// <summary>
    /// A two component vector class
    /// This vector used a right-handed coordinate system
    /// </summary>
    [StructLayout(LayoutKind.Sequential, Pack = 1)]
    [TypeConverter(typeof(Vector2Converter))]
    [DataContract]
    public struct Vector2
    {
        /// <summary>
        /// X component
        /// </summary>
        [DataMember(Name = "X")]
        private double xcomponent;

        /// <summary>
        /// Y component
        /// </summary>
        [DataMember(Name = "Y")]
        private double ycomponent;

        /// <summary>
        /// Initializes a new instance of the Vector2 struct.
        /// </summary>
        /// <param name="x">X component</param>
        /// <param name="y">Y component</param>
        public Vector2(double x, double y)
        {
            this.xcomponent = x;
            this.ycomponent = y;
        }

        /// <summary>
        /// Initializes a new instance of the Vector2 struct.
        /// </summary>
        /// <param name="v">Vector to copy</param>
        public Vector2(Vector2 v)
        {
            this.xcomponent = v.xcomponent;
            this.ycomponent = v.ycomponent;
        }

        /// <summary>
        /// Initializes a new instance of the Vector2 struct.
        /// </summary>
        /// <param name="v">The 3 vector</param>
        public Vector2(Vector3 v)
        {
            this.xcomponent = v.X;
            this.ycomponent = v.Y;
        }

        /// <summary>
        /// Initializes a new instance of the Vector2 struct.
        /// </summary>
        /// <param name="v">The 3 vector</param>
        public Vector2(Vector4 v)
        {
            this.xcomponent = v.X;
            this.ycomponent = v.Y;
        }

        /// <summary>
        /// Gets a vector that represents the +X axis.
        /// </summary>
        /// <returns></returns>
        public static Vector2 XAxis
        {
            get
            {
                return new Vector2(1.0, 0.0);
            }
        }

        /// <summary>
        /// Gets a vector that represents the -X axis.
        /// </summary>
        /// <returns></returns>
        public static Vector2 NegativeXAxis
        {
            get
            {
                return new Vector2(-1.0, 0.0);
            }
        }

        /// <summary>
        /// Gets a vector that represents the +Y axis.
        /// </summary>
        /// <returns></returns>
        public static Vector2 YAxis
        {
            get
            {
                return new Vector2(0.0, 1.0);
            }
        }

        /// <summary>
        /// Gets a vector that represents the -Y axis.
        /// </summary>
        /// <returns></returns>
        public static Vector2 NegativeYAxis
        {
            get
            {
                return new Vector2(0.0, -1.0);
            }
        }

        /// <summary>
        /// Gets or sets x component
        /// </summary>
        [Description("The X component of the vector.")]
        public double X
        {
            get
            {
                return this.xcomponent;
            }

            set
            {
                this.xcomponent = value;
            }
        }

        /// <summary>
        /// Gets or sets y component
        /// </summary>
        [Description("The Y component of the vector.")]
        public double Y
        {
            get
            {
                return this.ycomponent;
            }

            set
            {
                this.ycomponent = value;
            }
        }

        /// <summary>
        /// Returns a vector pointing in the opposite direction.
        /// </summary>
        /// <param name="value">Source vector.</param>
        /// <returns>Vector pointing in the opposite direction.</returns>
        public static Vector2 operator -(Vector2 value)
        {
            return new Vector2(-value.xcomponent, -value.ycomponent);
        }

        /// <summary>
        /// Vector2 operator +
        /// </summary>
        /// <param name="left">Left side</param>
        /// <param name="right">Right side</param>
        /// <returns>The vector result</returns>
        public static Vector2 operator +(Vector2 left, Vector2 right)
        {
            return new Vector2(
                left.xcomponent + right.xcomponent, 
                left.ycomponent + right.ycomponent);
        }

        /// <summary>
        /// Vector2 operator -
        /// </summary>
        /// <param name="left">Left side</param>
        /// <param name="right">Right side</param>
        /// <returns>The vector result</returns>
        public static Vector2 operator -(Vector2 left, Vector2 right)
        {
            return new Vector2(
                left.xcomponent - right.xcomponent, 
                left.ycomponent - right.ycomponent);
        }

        /// <summary>
        /// Vector2 operator /
        /// </summary>
        /// <param name="v">Vector divisor</param>
        /// <param name="value">Value to divide by</param>
        /// <returns>The vector result</returns>
        public static Vector2 operator /(Vector2 v, double value)
        {
            return new Vector2(v.xcomponent / value, v.ycomponent / value);
        }

        /// <summary>
        /// Vector2 operator *
        /// </summary>
        /// <param name="v">Vector to multiply</param>
        /// <param name="value">Value to multiply by</param>
        /// <returns>The vector result</returns>
        public static Vector2 operator *(Vector2 v, double value)
        {
            return new Vector2(v.xcomponent * value, v.ycomponent * value);
        }

        /// <summary>
        /// Vector2 operator *
        /// </summary>
        /// <param name="value">Value to multiply by</param>
        /// <param name="v">Vector to multiply</param>
        /// <returns>The vector result</returns>
        public static Vector2 operator *(double value, Vector2 v)
        {
            return new Vector2(v.xcomponent * value, v.ycomponent * value);
        }

        /// <summary>
        /// Dot product
        /// </summary>
        /// <param name="left">Left side</param>
        /// <param name="right">Right side</param>
        /// <returns>Scalar result</returns>
        public static double Dot(Vector2 left, Vector2 right)
        {
            return (left.xcomponent * right.xcomponent) + (left.ycomponent * right.ycomponent);
        }

        /// <summary>
        /// Convert from Vector2 to Vector3
        /// </summary>
        /// <param name="v">Vector to convert</param>
        /// <returns>Vector result</returns>
        public static Vector3 ToVector3(Vector2 v)
        {
            return new Vector3(v.X, v.Y, 0);
        }

        /// <summary>
        /// Normalize a vector to a unit vector
        /// </summary>
        /// <param name="v">Vector to be normalized</param>
        /// <returns>Normalized vector</returns>
        public static Vector2 Normalize(Vector2 v)
        {
            if (v.X != 0 || v.Y != 0)
            {
                double mag = v.L2Norm();
                double normalizationFactor = 1 / mag;
                return new Vector2(
                    v.X * normalizationFactor,
                    v.Y * normalizationFactor);
            }
            else
            {
                return new Vector2(0, 0);
            }
        }

        /// <summary>
        /// The equals operator for reference types
        /// </summary>
        /// <param name="leftSide">Vector on the left side</param>
        /// <param name="rightSide">Vector on the right side</param>
        /// <returns>Are the vectors values equal</returns>
        public static bool operator ==(Vector2 leftSide, Vector2 rightSide)
        {
            // Return true if the fields match:
            return Math.Abs(leftSide.X - rightSide.X) < MathConstants.ErrorEpsilon &&
                Math.Abs(leftSide.Y - rightSide.Y) < MathConstants.ErrorEpsilon;
        }

        /// <summary>
        /// The not equals operator for reference types
        /// </summary>
        /// <param name="leftSide">Vector on the left side</param>
        /// <param name="rightSide">Vector on the right side</param>
        /// <returns>Comparison result</returns>
        public static bool operator !=(Vector2 leftSide, Vector2 rightSide)
        {
            return !(leftSide == rightSide);
        }

        /// <summary>
        /// Retrieves a string representation of the Vector2.
        /// </summary>
        /// <returns>String that represents the Vector2.</returns>
        public override string ToString()
        {
            return string.Format("X:{0} Y:{1}", this.xcomponent, this.ycomponent);
        }

        /// <summary>
        /// Get the length of the vector
        /// </summary>
        /// <returns>Vector length</returns>
        public double Length()
        {
            return this.L2Norm();
        }

        /// <summary>
        /// Get the L2 (Euclidean) norm of the vector
        /// </summary>
        /// <returns>Vector length</returns>
        public double L2Norm()
        {
            return
                Math.Sqrt(
                    (this.xcomponent * this.xcomponent) + (this.ycomponent * this.ycomponent));
        }

        /// <summary>
        /// Returns the distance from the given vector.
        /// </summary>
        /// <param name="v"> Vector to measure distance to. </param>
        /// <returns> Distance to <c>v</c>. </returns>
        public double DistanceFrom(Vector2 v)
        {
            return (this - v).L2Norm();
        }

        /// <summary>
        /// Checks for equality of two Vectors. This is for value types
        /// </summary>
        /// <param name="obj">Vector to be compared</param>
        /// <returns>Comparison result</returns>
        public override bool Equals(object obj)
        {
            if (!(obj is Vector2))
            {
                return false;
            }

            Vector2 v = (Vector2)obj;

            return (Math.Abs(this.xcomponent - v.xcomponent) < MathConstants.ErrorEpsilon)
                   && (Math.Abs(this.ycomponent - v.ycomponent) < MathConstants.ErrorEpsilon);
        }

        /// <summary>
        /// Returns HashCode of object.
        /// </summary>
        /// <returns>Hashcode result</returns>
        public override int GetHashCode()
        {
            return base.GetHashCode();
        }
    }
}
